<template>
  <!-- 结算界面-现金处理键盘块 -->
  <div class="number-keyboard">
    <div class="right_content_input">
      <lay-row>
        <lay-col md="16">
          <lay-input v-model="setPayAmount">
            <template #prepend="{ disabled }">结算金额</template>
            <template #append="{ disabled }"><lay-icon type="layui-icon-close"
                @click="payAmountShowNULL"></lay-icon></template>
          </lay-input>
        </lay-col>
        <lay-col md="8">
          <span style="
              margin-left: 10px;
              color: red;
              font-size: 16px;
              font-weight: 600;
              display: block;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            ">{{ GiveChange }}</span>
        </lay-col>
      </lay-row>
    </div>
    <div class="right_content_numkeyboard">
      <div class="keyboard-num">
        <div class="keyboard-num-item" v-for="item in btnList" :key="item.key">
          <lay-button type="default" @click="clickBtn(item)">{{
            item.value
          }}</lay-button>
        </div>
      </div>
      <!-- 推荐金额 -->
      <div class="keyboard-recommend">
        <div class="keyboard-recommend-item" v-for="item in recommendList" :key="item.key">
          <lay-button type="normal" @click="setAmont(item)">{{
            item.value
          }}</lay-button>
        </div>
      </div>

      <div class="keyboard-option">
        <div class="keyboard-option-item">
          <lay-button type="primary" @click="balanceMethod">结算</lay-button>
        </div>
        <div class="keyboard-option-item">
          <lay-button @click="putOrder()">挂单</lay-button>
        </div>
        <div class="keyboard-option-item">
          <lay-button type="danger" @click="payExit()">退出</lay-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, watch, onMounted, computed } from "vue";
import XEUtils, { first } from "xe-utils";
import { HTTP_pay } from "@/apis/cashierApi";
import { layer } from "@layui/layui-vue";

const props = defineProps({
  PAY_DB: {
    receivable: {
      type: Number,
      default: 0, //应收
      required: true,
    },
    received: {
      type: Number,
      default: 0, //已收
      required: true,
    },
    pendingPayment: {
      type: Number,
      default: 0, //待收
      required: true,
    },
  },
  order_db: {
    dbid: {
      type: String,
      default: "", //单号
      required: true,
    },
    sign: {
      type: String,
      default: "", //改单签名串
      required: true,
    },
  },
});

/** 支付金额 */
const setPayAmount = ref("");
/** 找零金额 */
const GiveChange = ref("");
/**找零金额计算 */
const GiveChange_fn = () => {
  let a = 0;
  a = XEUtils.subtract(props.PAY_DB.pendingPayment, XEUtils.toNumber(setPayAmount.value));
  if (a < 0) {
    GiveChange.value = "找零:" + XEUtils.toString(Math.abs(a)); //绝对值后转字符串
  } else {
    GiveChange.value = "";
  }
  if (a <= -100) {
    layer.msg("注意金额", { icon: 7 });
  }
  // console.log("找零金额计算", GiveChange.value);
};

/** 数字键盘*/
const btnList = ref([
  { key: 7, value: "7" },
  { key: 8, value: "8" },
  { key: 9, value: "9" },
  { key: 4, value: "4" },
  { key: 5, value: "5" },
  { key: 6, value: "6" },
  { key: 1, value: "1" },
  { key: 2, value: "2" },
  { key: 3, value: "3" },
  { key: 0, value: "0" },
  { key: ".", value: "." },
  { key: "back", value: "回退" },
  { key: 10, value: "00" },
  { key: 11, value: "000" },
  { key: "clear", value: "清空" },

]);

/** 支付挂单 */
const putOrder = () => {
  console.log("支付挂单");
};


/** 推荐金额点击*/
const setAmont = (item) => {
  // console.log("推荐金额点击-->", item);
  setPayAmount.value = item.value;
};

/** 金额框清零 */
const payAmountShowNULL = async () => {
  // console.log("金额框清零-->");
  setPayAmount.value = ""; //支付金额
};

/** 结算点击 */
const balanceMethod = async () => {
  let payAmount_Number = XEUtils.toNumber(setPayAmount.value); //转数字
  if (payAmount_Number <= 0) {
    layer.msg("注意金额：" + payAmount_Number, { time: 2000, icon: 7 });
    return;
  }

  const params = {
    dbid: props.order_db.dbid, //销售单号
    sign: props.order_db.sign, //签名串
    payway: 9, //支付方式_9现金8聚合支付
    total_amount: setPayAmount.value, //交易金额

    dynamic_id: "", //支付码（支付宝或微信条码号-线上支付时必填）-现金支付时不验证
    pay_currency: "RMB", //支付币种-在线支付时不验证
    operator: "工号1001", //门店操作员
    remark: "支付备注-现金支付", //备注
  };
  console.log("结算请求数据-->", params);
  const res = await HTTP_pay(params);
  console.log("结算HTTP回调", res);

  if (res.code == 200) {
    pay_res(res); //支付后_向上级组件响应
    payAmountShowNULL(); //金额框清零

    if (res.order_db.state == "B") {
      if (res.money.give_change != 0) {
        let contenthtml = '<span style="display:flex;color:red;font-size:24px;font-weight:600;">'
          + '找零：' + res.money.give_change
          + '</br>收到：' + res.money.total_amount
          + '</br>入账：' + res.money.money_in
          + '</span>';
        layer.open({
          type: "0",//
          shadeClose: false,//遮盖层关闭
          shadeOpacity: "0.8",//遮盖层透明度
          closeBtn: false,//关闭按钮
          title: false,//标题
          // time: 60000,//关闭时间
          // area: ["500px", "300px"],//尺寸
          isHtmlFragment: true,//解析 html 字符
          content: contenthtml,//标题
        });
        contenthtml = "";
      }
    }
  } else {
    layer.msg(res.msg, { time: 2000, icon: 7 });
  }
};

const emit = defineEmits(["pay_res", "windowClose_1"]); //子父组件通讯
/** 支付后_向上级组件响应 */
function pay_res(item) {
  console.log("支付后_向上级组件响应", item);
  emit("pay_res", item);
}
/** 结算退出 */
const payExit = () => {
  console.log("结算退出");
  emit("windowClose_1", "结算退出"); //让上级组件弹窗关闭
};

/**点击数字键盘事件 */
const clickBtn = (item) => {
  // console.log("点击数字键盘", item.value);
  let num = "";
  num = setPayAmount.value == "." ? "0." : XEUtils.toString(setPayAmount.value);
  //删除一个数
  if (item.key === "back") {
    if (num.length > 0) {
      num = num.slice(0, -1);
    }
  } else if (item.key == ".") {
    // 只能有一个小数点
    if (num.indexOf(".") === -1) {
      num += ".";
    }
  } else if (item.key == "clear") {
    num = "";
  } else {
    //点击的数字
    num += item.value;
  }
  setPayAmount.value = num;
  if (setPayAmount.value.includes(".") == false) {
    if (setPayAmount.value.length > 1) {
      // console.log("没小数点且长度大于1,如果首位为0,用正则删除0", setPayAmount.value);
      setPayAmount.value = setPayAmount.value.replace(/^0+/, ""); //如果首位为0用正则删除
    }
  }


};

/** 推荐金额 */
const recommendList = ref([
  { key: 10, value: "10" },
  { key: 20, value: "20" },
  { key: 50, value: "50" },
  { key: 100, value: "100" },
]);
/** 初始化推荐金额按钮 */
const setRecMonentMonet = (money) => {
  console.log("初始化推荐金额按钮", XEUtils.getType(money), money);
  money = XEUtils.toNumber(money);
  if (money <= 0) {
    recommendList.value = [
      { key: 0, value: "0" },
      { key: 1, value: "0" },
      { key: 2, value: "0" },
      { key: 3, value: "0" },
      { key: 4, value: "0" },
    ];
    return;
  }
  let fristMoney = XEUtils.ceil(money);
  let secondMoney = XEUtils.ceil(fristMoney / 10) * 10;
  if (secondMoney == fristMoney) {
    secondMoney = XEUtils.ceil(XEUtils.add(secondMoney, 10));
  }
  let thirdMoney = XEUtils.ceil(secondMoney / 100) * 100;
  if (secondMoney == thirdMoney) {
    secondMoney = XEUtils.ceil(XEUtils.add(secondMoney, 100));
  }
  let fourthMoney = XEUtils.ceil(XEUtils.add(thirdMoney, 100));
  const arr = [
    { key: XEUtils.toString(money), value: XEUtils.toString(money) },
    { key: XEUtils.toString(fristMoney), value: XEUtils.commafy(fristMoney, { digits: 0 }) },
    { key: XEUtils.toString(secondMoney), value: XEUtils.commafy(secondMoney, { digits: 0 }) },
    { key: XEUtils.toString(thirdMoney), value: XEUtils.commafy(thirdMoney, { digits: 0 }) },
    { key: XEUtils.toString(fourthMoney), value: XEUtils.commafy(fourthMoney, { digits: 0 }) },
  ];
// 过滤重复
  function removeDuplicates(arr) {
    let unique = [];
    let found = {};
    arr.forEach(item => {
      let s = JSON.stringify(item);
      if (!found[s]) {
        unique.push(item);
        found[s] = true;
      }
    });
    return unique;
  }
  const result = removeDuplicates(arr);
  console.log("过滤重复前", XEUtils.getType(arr), arr);
  console.log("过滤重复后", XEUtils.getType(result), result);

  recommendList.value = result;

};

const initPage = () => {
  //拿不到数据, 设置100ms后执行
  setTimeout(() => {
    console.log("props数据", props.PAY_DB.pendingPayment, props.order_db.dbid);
    setRecMonentMonet(props.PAY_DB.pendingPayment); //初始化推荐金额按钮
  }, 1000);
};

/** 监听支付金额setPayAmount变化 */
watch(setPayAmount, (value) => {
  // console.log("监听支付金额setPayAmount变化-->", XEUtils.getType(value), value);
  GiveChange_fn(); //找零金额计算
});

onMounted(() => {
  initPage();
});
//向父组件暴露子组件的方法或者数据
defineExpose({
  setRecMonentMonet,
});
</script>

<style lang="less" scoped>
.number-keyboard {
  height: 100%;
  width: 100%;
  background: #eee;

  // display: flex;
  // justify-content: space-between;
  .right_content_input {
    height: 36px;
    width: 100%;
    line-height: 36px;
    padding: 5px;
    box-sizing: border-box;

    .t_title_col {
      text-align: center;
      background: #ffbca7;
    }

    .layui-col :deep(.layui-input .layui-input-wrapper input) {
      text-align: end;
      padding-right: 20px;
    }
  }

  .right_content_numkeyboard {
    height: calc(100% - 40px);
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .keyboard-num {
    width: 47%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;

    .keyboard-num-item {
      width: 33.33%;
      display: flex;
      justify-content: center;
      align-items: center;

      button {
        width: 80px;
        height: 50px;
        background: #fff;
      }
    }
  }

  .keyboard-recommend {
    width: 24%;
    height: 100%;
    padding: 5px 0 5px 0;
    display: flex;
    flex-wrap: wrap;

    .keyboard-recommend-item {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      button {
        width: 100%;
        height: 42px;
      }
    }
  }

  .keyboard-option {
    width: 24%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;

    .keyboard-option-item {
      width: 100%;
      height: 80px;
      display: flex;

      button {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
